package com.chen.shopping_manager_api.securityhandler;

import com.chen.shopping_common.pojo.Admin;
import com.chen.shopping_common.pojo.Permission;
import com.chen.shopping_common.service.AdminService;
import com.chen.shopping_common.service.PermissionService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDeteils implements UserDetailsService {

    @DubboReference
    private AdminService adminService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //认证
        Admin admin = adminService.findAdminByUsername(username);
        if(admin == null){
            throw new UsernameNotFoundException("用户名不存在");
        }

        //授权
        List<Permission> permissions = adminService.findPermissionByUsername(username);
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

            for (Permission permission : permissions) {
                grantedAuthorities.add(new SimpleGrantedAuthority(permission.getUrl()));
            }




        //封装UserDetails对象
        UserDetails userDetails = User.withUsername(admin.getUsername()).password(admin.getPassword()).authorities(grantedAuthorities).build();

        return userDetails;
    }
}
